package com.springboot.blog.controller.order;

import com.springboot.blog.beans.BlogOrder;
import com.springboot.blog.dao.OrderDao;
import com.springboot.blog.dao.SignInMapper;
import com.springboot.blog.service.impl.OrderPayServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *  支付宝支付，控制器
 *
 * @author wangziyang
 * */
@RestController
@RequestMapping(value = "/pay")
@AllArgsConstructor
public class PayController {

    private OrderPayServiceImpl payService;
    @Resource
    private OrderDao orderDao;
    @Resource
    private SignInMapper signInMapper;

    /**
     * 下单支付
     */
    @RequestMapping(value = "/confirm", produces = {"text/html;charset=UTF-8"})
    public Object pay(String bigDecimal) throws Exception {
        //这个接口其实应该是post方式的，但是我这里图方便，直接以get方式访问，
        //且返回格式是text/html，这样前端页面就能直接显示支付宝返回的html片段
        //真实场景下由post方式请求，返回code、msg、data那种格式的标准结构，让前端拿到data里的
        //html片段之后自行加载

        //由于我这里并没有真正的传参数，所以象征性的new一下，避免空指针
        return payService.pay("充值余额", bigDecimal);
    }

    @PostMapping(value = "/notify")
    @Transactional
    public String notify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = new HashMap<String, String>();
        //从支付宝回调的request域中取值
        Map<String, String[]> requestParams = request.getParameterMap();

        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        //商品订单号
        String out_trade_no = request.getParameter("out_trade_no");            // 商户订单号
        // 当前交易状态
        String tradeStatus = request.getParameter("trade_status");            //交易状态
        // 支付金额
        String totalAmount = request.getParameter("total_amount");            //交易状态
        // 支付时间
        String payDate = request.getParameter("gmt_payment");            //交易状态
        //3.签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        System.out.println("=========交易状态======"+tradeStatus);
        System.out.println("===========余额=========="+totalAmount);
        System.out.println("===========商户订单号=========="+out_trade_no);
        System.out.println("===========支付时间=========="+payDate);
        String  userName = (String) request.getServletContext().getAttribute("userName");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(payDate);
            BlogOrder blogOrder = new BlogOrder();
            blogOrder.setOrderUsername(userName);
            blogOrder.setOrderNumber(Long.valueOf(out_trade_no));
            blogOrder.setOrderBalance(Double.parseDouble(totalAmount));
            blogOrder.setOrderStatus(tradeStatus.equals("TRADE_SUCCESS")?1:0);
            blogOrder.setOrderTime(date);
            orderDao.insert(blogOrder);

            signInMapper.updateReward(userName,Double.parseDouble(totalAmount)*2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "failure";
    }
}
